package com.common;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class FileReaderUtils {


    public static Map<String, FileReader> fileReaderMap = new HashMap<>();

    public static Map<String, LineNumberReader> lineNumberReaderMap = new HashMap<>();

    /**
     * 根据path路径获取fileReader对象
     * @param path
     * @return
     * @throws FileNotFoundException
     */
    public static FileReader getFileReader(String path) throws FileNotFoundException {
        if (!fileReaderMap.containsKey(path)) {
            FileReader fileReader = new FileReader(path);
            fileReaderMap.put(path, fileReader);
        }
        return fileReaderMap.get(path);
    }

    /**
     * 根据path路径获取lineNumberReader对象
     * @param path
     * @return
     * @throws FileNotFoundException
     */
    public static LineNumberReader getLineNumberReader(String path) throws FileNotFoundException {
        if (!lineNumberReaderMap.containsKey(path)) {
            FileReader fileReader = getFileReader(path);
            LineNumberReader lineNumberReader = new LineNumberReader(fileReader);
            lineNumberReaderMap.put(path, lineNumberReader);
        }
        return lineNumberReaderMap.get(path);
    }

    /**
     * 读取下一行
     * @param path
     * @return
     */
    public static String readNextLine(String path) {
        String value = null;
        try {
            LineNumberReader lineNumberReader = getLineNumberReader(path);
            value = lineNumberReader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return value;
    }


    public static void close(String path) throws IOException {
        if (fileReaderMap.containsKey(path)) {
            FileReader fileReader = fileReaderMap.get(path);
            fileReader.close();
        }
    }

    public static void close() throws IOException {
        Set<String> paths = fileReaderMap.keySet();
        for (String path : paths) {
            close(path);
        }
    }

    public static void main(String[] args) {
    }

}
